package app;

import com.sun.spot.resources.Resources;
import com.sun.spot.resources.transducers.Condition;
import com.sun.spot.resources.transducers.IAnalogInput;
import com.sun.spot.resources.transducers.IConditionListener;
import com.sun.spot.resources.transducers.IIOPin;
import com.sun.spot.resources.transducers.ILightSensor;
import com.sun.spot.resources.transducers.IMeasurementRange;
import com.sun.spot.resources.transducers.ITriColorLEDArray;
import com.sun.spot.resources.transducers.LEDColor;
import com.sun.spot.resources.transducers.LightSensorEvent;
import com.sun.spot.resources.transducers.SensorEvent;

import com.sun.spot.sensorboard.EDemoBoard;
import com.sun.spot.sensorboard.peripheral.ADT7411Event;
import com.sun.spot.sensorboard.peripheral.IADT7411ThresholdListener;
import com.sun.spot.sensorboard.peripheral.LightSensor;  
import com.sun.spot.util.Utils;

import java.io.IOException;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;

/**
 * Display the light sensor reading in white
 */

public class EnergyCare extends MIDlet implements IADT7411ThresholdListener, 
       IConditionListener {
    
    private ILightSensor light = 
        (ILightSensor) Resources.lookup(ILightSensor.class);
    private IAnalogInput analogIn = 
        (IAnalogInput) Resources.lookup(IAnalogInput.class, "A0");
    private ITriColorLEDArray leds = 
        (ITriColorLEDArray) Resources.lookup(ITriColorLEDArray.class);
    
    Condition lightCheck = null;
    
    protected void startApp() throws MIDletStateChangeException {

        /**
         * Monitora se a luz esta abaixo de 740 (1480 lux - dia nublado claro)
         */

        // Se houver monitoramento de condicao de intervalo por hardware
        //if (light instanceof com.sun.spot.sensorboard.peripheral.LightSensor) {

            //com.sun.spot.sensorboard.peripheral.LightSensor lt = 
            //    (com.sun.spot.sensorboard.peripheral.LightSensor) light;
            //lt.addIADT7411ThresholdListener(this);
            //lt.setThresholds(10, 740); 
            //lt.enableThresholdEvents(true);

        // Senao por software
        //} else {

            // Checar a cada dez segundos a condicao especificada em isMet
            lightCheck = new Condition(light, this, 10 * 1000) { 
                public boolean isMet(SensorEvent evt) throws IOException {
                    int val = ((LightSensorEvent)evt).getValue();
                    if (val <= 740) {
                        // Condicao foi satisfeita: parar verificacao 
                        // e retornar true para os listeners
                        stop();         
                        return true;                        
                    } else {
                        // Condicao nao satisfeita
                        return false;                      
                    }
                }
            };
            // Comecar o monitoramento da condicao
            lightCheck.start();

        }
       
        /**
         * Faz a leitura da luminosidade e mapeia para o painel de LEDs
         */

        int ledsOn = 0;
        leds.setColor(LEDColor.WHITE);
        while (true) {
            try {
                ledsOn = light.getValue() / 84;     // [0, 750] = [0, 8]
                for (int i = 0; i < 8; i++) {
                    leds.getLED(i).setOn(i < ledsOn);
                }
                Utils.sleep(200);
            } catch (IOException ex) {
                // ignore sensor errors
            }
        }
    }
    
    protected void pauseApp() {
        // This will never be called by the Squawk VM
    }
    
    protected void destroyApp(boolean arg0) throws MIDletStateChangeException {
        // Only called if startApp throws any exception other than MIDletStateChangeException
    }

    /**
     * Rev8 sensorboard callback for when the light sensor value goes above or below
     * the specified thresholds.
     *
     * @param sensor the sensor being monitored.
     * @param condition the condition doing the monitoring.
     */
    public void conditionMet(SensorEvent evt, Condition condition) {
        System.out.println("Limite de luz excedido: " + ((LightSensorEvent)evt).getValue());
        Utils.sleep(2000);
        lightCheck.start();
    }

    /**
     * Rev6 sensorboard callback for when the light sensor value goes above or below
     * the specified thresholds.
     * 
     * @param light the ILightSensor that has crossed a threshold.
     * @param val the current light sensor reading.
     */
    public void thresholdExceeded(ADT7411Event evt) {
        System.out.println("Limite de luz excedido: " + evt.getValue());
        Utils.sleep(2000);
        ((LightSensor)evt.getSensor()).enableThresholdEvents(true);      // re-enable notification
    }

    /**
     * Callback for when the light sensor thresholds are changed.
     * 
     * @param light the ILightSensor that had its threshold values changed.
     * @param low the new light sensor low threshold value.
     * @param high the new light sensor high threshold value.
     */
    public void thresholdChanged(ADT7411Event evt) {
    }

}
